﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using Graffiti.Core;
using GraffitiExtras.Extensions.InstalledThemes;

namespace GraffitiExtras.Plugins.ThemeExplorer
{
    public class ThemeExplorer : GraffitiEvent
    {

        public override string Name
        {
            get
            {
                return "Theme Explorer";
            }
        }

        public override string Description
        {
            get
            {
                return
                    "Plug-in that allows you to change the theme dynamically via the ThemeName Cookie. " +
                    "Created by <a href=\"http://graffiticmstips.com\">Brian Zalk</a>.";
            }
        }
        public override void Init(GraffitiApplication ga)
        {
            ga.BeginRequest += new EventHandler(ga_BeginRequest);
        }

        void ga_BeginRequest(object sender, EventArgs e)
        {
            const string COOKIE_NAME = "ThemeName";
            string queryThemeName = HttpContext.Current.Request.QueryString[COOKIE_NAME];
            List<string> themeNameList = new InstalledThemes().InstalledThemesList();

            if (queryThemeName != null && themeNameList.Contains(queryThemeName))
            {
                HttpContext.Current.Response.Cookies.Add(new HttpCookie(COOKIE_NAME, queryThemeName));
                GraffitiContext.Current.Theme = queryThemeName;
            }
            else
                if (HttpContext.Current.Request.Cookies[COOKIE_NAME] != null && themeNameList.Contains(HttpContext.Current.Request.Cookies[COOKIE_NAME].Value))
                    GraffitiContext.Current.Theme = HttpContext.Current.Request.Cookies[COOKIE_NAME].Value;
        }
    }
}
